"""
订单数据模型类

"""
import json

from peewee import *
from playhouse.shortcuts import model_to_dict

from .base_model import BaseModel
from .erp import ErpCheck, ErpQuotation, District, ErpDictDate, ErpQuotationToCustomer
from .user import Organization, User, UserOrg


class Order(BaseModel):
    VLL_TYPE_MAP = (('p2p', '专线接入'),
                    ('multi', '企业组网'),
                    ('NNI', 'NNI'),
                    )
    type = CharField(max_length=200, verbose_name='业务类型', choices=VLL_TYPE_MAP, null=True)
    # 订单发起方
    create_by_org = ForeignKeyField(Organization, on_delete='CASCADE', verbose_name='订单发起方',
                                    backref='start_order', null=True)
    # 下单账号
    create_by_member = ForeignKeyField(User, on_delete='CASCADE', verbose_name='订单发起人',
                                       backref='create_memer', null=True)
    # 报价时间
    offer_time = DateTimeField(default=None, verbose_name="报价时间", null=True)
    # 实施时间
    implementation_time = DateTimeField(default=None, verbose_name="实施时间", null=True)
    # 到期时间
    expire_time = DateTimeField(default=None, verbose_name="到期时间", null=True)
    # 订单期限
    deadline = CharField(max_length=200, verbose_name='订单期限', null=True)
    # 订单状态
    STATUS_MAP = (('offered', "已报价"),
                  ('offering', '报价中'),
                  ('waiting_offer', '待报价'),
                  ('confirm_offer', '确认报价'),
                  ('refuse_offer', '拒绝报价'),
                  ('offer_expire', '报价已过期'),
                  )
    status = CharField(max_length=200, verbose_name='订单状态', choices=STATUS_MAP, null=True)
    description = TextField(verbose_name='订单描述', null=True)
    # 点到点{'a_point':{},'z_point':{},'info':{}}
    # 为虚拟组网时[{'point': {}, 'info': {}}]
    # 端口类型 [{'point': {}, 'info': {}}]
    # info代表详细需求
    # params = models.JSONField(verbose_name='订单参数', null=True)  # 订单点的参数
    params = TextField(verbose_name='订单参数', null=True)  # 订单点的参数
    no = CharField(max_length=255, verbose_name='订单编号', null=True)

    class Meta:
        db_table = 'xingxiu_order'

    def get_standard_obj(self):
        """
        订单信息
        """
        order = model_to_dict(self)
        org = Organization.get_or_none(Organization.id == self.create_by_org.id)
        order['create_by_org'] = {"id": org.id, 'name': org.name}
        order['create_by_member'] = {"id": self.create_by_member.id, 'name': self.create_by_member.name}
        order['params'] = json.loads(order['params'])
        order_details = OrderDetail.select().where(OrderDetail.order_id == self.id)
        order['products'] = []
        for detail in order_details:
            order['products'].append(detail.get_standard_obj())
        # order方案报价
        # 1.通过星宿订单id,去找erp的核查方案,找到erp的方案报价并展示
        order['erp_offer_plan'] = []
        if order['status'] not in ['waiting_offer', 'offering']:
            erps = ErpQuotationToCustomer.select().where(ErpQuotationToCustomer.demand_id == self.no,
                                                         ErpQuotationToCustomer.deleted == False)
            if erps:
                for erp in erps:
                    info = model_to_dict(erp)
                    print(info)
                    info['monthly_quotation'] = info['monthly_quotation'] / 100 if info['monthly_quotation'] else 0
                    info['one_time_quotation'] = info['one_time_quotation'] / 100 if info['one_time_quotation'] else 0
                    currency = ErpDictDate.select(ErpDictDate.label).where(ErpDictDate.dict_type == 'erp_currency',
                                                                           ErpDictDate.value == info['currency'])
                    product_type = ErpDictDate.select(ErpDictDate.label).where(ErpDictDate.dict_type == 'erp_prod_type',
                                                                               ErpDictDate.value == info['product_type']
                                                                               )
                    info['currency'] = currency[0].label
                    info['product_type'] = product_type[0].label
                    order['erp_offer_plan'].append(info)
        return order


class OrderDetail(BaseModel):
    """
    订单详情即每一个产品
    # 标准
    # 点到点：节点名称、节点位置、节点类型、参考价格
    # 组网：节点类型、节点名称、节点位置、带宽、购买时长、产品价格
    # 非标准
    # 接入位置(国家、省份、城市)、详细地址
    """
    order = ForeignKeyField(Order, on_delete='CASCADE', verbose_name='订单',
                            backref='order_detail', null=True)
    product = CharField(max_length=200, verbose_name='产品名称', null=True,
                        )  # 后台中的价格的分类 端口=拼pop点名称 云=xx云 线=dci 非标：定制需求
    product_type = CharField(max_length=200, verbose_name='产品类型', null=True)
    # price = models.JSONField(max_length=200, verbose_name='产品价格', null=True)  # {month:100,once:10}
    price = TextField(verbose_name='产品价格', null=True)  # {month:100,once:10}
    period = IntegerField(verbose_name='产品周期', null=True)  #
    location = CharField(max_length=255, verbose_name='位置', null=True)
    # product_params = models.JSONField(verbose_name='产品参数', null=True)
    product_params = TextField(verbose_name='产品参数', null=True)
    note = CharField(max_length=255, verbose_name='备注', null=True)

    def get_standard_obj(self):
        order_detail = model_to_dict(self, exclude=[OrderDetail.order])
        order_detail['product_params'] = json.loads(order_detail['product_params'])
        order_detail['price'] = json.loads(order_detail['price'])
        return order_detail

    class Meta:
        db_table = 'xingxiu_order_detail'


class OrderLog(BaseModel):
    order = ForeignKeyField(Order, on_delete='CASCADE', verbose_name='订单',
                            backref='order_log', null=True)
    operator = ForeignKeyField(User, on_delete='CASCADE', verbose_name='操作人',
                               backref='member_order_log', null=True)
    operate_code = CharField(max_length=40, verbose_name='操作内容', null=True)  # 比如 创建订单、修改订单、报价、确认报价、实施等
    content = TextField(verbose_name='操作内容', null=True)
    to_status = CharField(max_length=40, verbose_name='操作后状态', null=True)  # 选项与订单状态同

    class Meta:
        db_table = 'xingxiu_order_log'

    def get_standard_obj(self, request):
        return model_to_dict(self)
